using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

[ExecuteInEditMode]
public class ResizableButton : MonoBehaviour
{
    public Text text;
    public Button button;
    public ContentSizeFitter contentSizeFitter;
    public int minWidth;
    public int maxWidth;
    public int leftPadding;
    public int rightPadding;
    private string _prevText = "";
    // Start is called before the first frame update
    void Awake()
    {
        text = GetComponentInChildren<Text>();
        contentSizeFitter = text.GetComponent<ContentSizeFitter>();
        button = GetComponent<Button>();
        DoLayout();
    }

    // Update is called once per frame
    void Update()
    {
        if (text.text != _prevText)
        {
            _prevText = text.text;
            DoLayout();
        }
    }

    void DoLayout()
    {
        var textMaxWidth = maxWidth - leftPadding - rightPadding;
        var preferredWidth = LayoutUtility.GetPreferredWidth(text.rectTransform);
        if (preferredWidth > textMaxWidth) // text is too long
        {
            contentSizeFitter.horizontalFit = ContentSizeFitter.FitMode.Unconstrained;
            text.rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, textMaxWidth);
            text.resizeTextForBestFit = true;
        }
        else
        {
            contentSizeFitter.horizontalFit = ContentSizeFitter.FitMode.PreferredSize;
            text.resizeTextForBestFit = false;
        }
        var btnWidth = Mathf.Clamp(preferredWidth + leftPadding + rightPadding, minWidth, maxWidth);
        button.GetComponent<RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, btnWidth);
    }
}
